import { BaseStorage } from './base-storage.js';

/**
 * localStorage存储实现
 */
export class LocalStorage extends BaseStorage {
  constructor() {
    super('localStorage');
  }

  /**
   * 检查localStorage是否可用
   * @returns {boolean} 是否可用
   */
  isAvailable() {
    try {
      const test = '__localStorage_test__';
      localStorage.setItem(test, test);
      localStorage.removeItem(test);
      return true;
    } catch (e) {
      return false;
    }
  }

  /**
   * 设置数据
   * @param {string} key - 键名
   * @param {any} value - 值
   * @param {Object} options - 选项
   * @returns {boolean} 是否成功
   */
  set(key, value, options = {}) {
    if (!this.isAvailable()) {
      console.error('localStorage is not available');
      return false;
    }

    try {
      const data = JSON.stringify(value);
      localStorage.setItem(key, data);
      return true;
    } catch (e) {
      console.error('Error setting localStorage item:', e);
      return false;
    }
  }

  /**
   * 获取数据
   * @param {string} key - 键名
   * @param {Object} options - 选项
   * @returns {any} 值
   */
  get(key, options = {}) {
    if (!this.isAvailable()) {
      console.error('localStorage is not available');
      return null;
    }

    try {
      const data = localStorage.getItem(key);
      if (data === null) {
        return null;
      }
      return JSON.parse(data);
    } catch (e) {
      console.error('Error getting localStorage item:', e);
      return null;
    }
  }

  /**
   * 删除数据
   * @param {string} key - 键名
   * @param {Object} options - 选项
   * @returns {boolean} 是否成功
   */
  remove(key, options = {}) {
    if (!this.isAvailable()) {
      console.error('localStorage is not available');
      return false;
    }

    try {
      localStorage.removeItem(key);
      return true;
    } catch (e) {
      console.error('Error removing localStorage item:', e);
      return false;
    }
  }

  /**
   * 清空存储
   * @param {Object} options - 选项
   * @returns {boolean} 是否成功
   */
  clear(options = {}) {
    if (!this.isAvailable()) {
      console.error('localStorage is not available');
      return false;
    }

    try {
      localStorage.clear();
      return true;
    } catch (e) {
      console.error('Error clearing localStorage:', e);
      return false;
    }
  }

  /**
   * 获取所有键
   * @param {Object} options - 选项
   * @returns {string[]} 键数组
   */
  keys(options = {}) {
    if (!this.isAvailable()) {
      console.error('localStorage is not available');
      return [];
    }

    const keys = [];
    for (let i = 0; i < localStorage.length; i++) {
      keys.push(localStorage.key(i));
    }
    return keys;
  }
}
